package com.bw.ivideo.testmvi.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.ivideo.testmvi.intent.VideoIntent
import com.bw.ivideo.testmvi.model.entity.VideoEntity
import com.bw.ivideo.testmvi.model.service.VideoService
import com.bw.ivideo.testmvi.state.VideoState
import com.bw.lib_mvicore.model.BaseModel
import com.bw.lib_net.entity.ResponseEntity
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/17 19:20
 * @Description :
 */
class VideoViewModel: BaseModel<VideoIntent>() {
    val service:VideoService by  lazy { VideoService() }

    private val _state = MutableStateFlow<VideoState>(VideoState.Init)
    val state: StateFlow<VideoState>
        get() = _state

    //处理意图
    override fun handleIntent() {

        viewModelScope.launch {

            intents.consumeAsFlow().collect{
                when (it) {
                    is VideoIntent.GetVideoIntent -> {
                        getVideoDatas(it.page,it.pagesize)
                    }
                }
            }


        }
    }

    private fun getVideoDatas(page: Int, pagesize: Int) {
        viewModelScope.launch {
            flow<ResponseEntity<MutableList<VideoEntity>>> {
                val videos = service.getVideos(page, pagesize)
                emit(videos)
            }.catch { e->
                _state.value = VideoState.Error(e.message.toString())
            }.filter {
                it != null
            }.collect{
                if(it.code == 0){
                    _state.value = VideoState.Success(it.data)
                }else{
                    _state.value = VideoState.Error(it.msg)
                }
            }

        }
    }


}